//
//  YYEExampleViewController.m
//  YuYingEDU
//
//  Created by zl on 2018/3/13.
//  Copyright © 2018年 胡波. All rights reserved.
//

#import "YYEExampleViewController.h"
#import "YYEExampleView.h"
#import "YYEScoreView.h"
#import "YYEScoreView1.h"
#import "HWQuestionsFooterView.h"
#import "NSStringExt.h"

@interface YYEExampleViewController ()<HWQuestionsFooterViewDelegate>

@property (nonatomic,strong) YYEExampleView *exampleView;
@property (nonatomic,strong) YYEScoreView *scoreView;
@property (nonatomic,strong) YYEScoreView1 *scoreView1;
@property (nonatomic, weak) HWQuestionsFooterView *footerView;

@property (nonatomic,strong) NSArray *datas;
@property (nonatomic,strong) NSArray *originDatas;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic,strong) NSDictionary *dic;


@end

@implementation YYEExampleViewController

- (YYEScoreView *)scoreView
{
    if (!_scoreView) {
        
        
//        __weak typeof(self) weakSelf = self;
        _scoreView = [[YYEScoreView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];

    }
    return _scoreView;
}

- (YYEScoreView1 *)scoreView1
{
    if (!_scoreView1) {
        
        
        //        __weak typeof(self) weakSelf = self;
        _scoreView1 = [[YYEScoreView1 alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
        
    }
    return _scoreView1;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    _exampleView = [[YYEExampleView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight-kTopHeight-45)];
    [self.view addSubview:_exampleView];
    
    __weak typeof(self) weakSelf = self;
    _exampleView.block = ^{// 答对回调
        
        if (self.mark == 1) {// 删除错题记录
            NSDictionary *dic = weakSelf.originDatas[weakSelf.page-1];
            [weakSelf deleteMyWrong:dic[@"wid"]];
        }
        
//        weakSelf.page++;
//        YYEExampleModel *model = weakSelf.datas[weakSelf.page-1];
//        [weakSelf.exampleView setModel:model page:weakSelf.page];
//
//        //刷新底部视图状态
//        [weakSelf reloadFooterViewState];
        
    };
    
    _exampleView.block1 = ^{// 答错回调

//        YYEExampleModel *model = weakSelf.datas[weakSelf.page-1];
//
//        NSLog(@"json:%@",model.mj_keyValues);
//        NSLog(@"jsonString:%@",[model.mj_keyValues mj_JSONString]);
        if (self.mark == 0) { // 查看答题和继续答题

            YYEExampleModel *model = weakSelf.datas[weakSelf.page-1];
            
            NSLog(@"json:%@",model.mj_keyValues);
            NSLog(@"jsonString:%@",[model.mj_keyValues mj_JSONString]);
            
            [weakSelf submitWrong:[model.mj_keyValues mj_JSONString]];
        }
    };
    
    //底部视图
    HWQuestionsFooterView *footerView = [[HWQuestionsFooterView alloc] initWithFrame:CGRectMake(0, _exampleView.jc_bottom, SCREEN_WIDTH, 45)];
    footerView.delegate = self;
    [self.view addSubview:footerView];
    self.footerView = footerView;
    footerView.mark = self.mark;

    if (self.mark == 0) { // 查看答题和继续答题

        // "process": 1, //进度(0未达到进度 1开始答题 2继续答题 3查看答题
        // "type": 2, // 1是习题 2是考试
        
        _exampleView.type = self.type;
        [self loadData];



    }
    else if (self.mark == 1)  {// 错题记录
        
        [self loadData1];

    }

    

    
    //初始化页码
    _page = 1;
}


- (void)configNavi {
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"保存" style:UIBarButtonItemStyleDone target:self action:@selector(saveClicked)];
    [self.navigationItem.rightBarButtonItem setTintColor:[UIColor blackColor]];
    
}



// 保存
- (void)saveClicked {
    
    [self.view endEditing:YES];
    
    if (self.mark == 0) { // 查看答题和继续答题
        
        if (self.type.integerValue == 2) {// 考试
            
            [self saveOrUp];
            
        }
        
        else {// 习题
            
            NSArray *dictArray = [YYEExampleModel mj_keyValuesArrayWithObjectArray:self.datas];
            NSString *content = [dictArray mj_JSONString];
            
            NSLog(@"content:%@",content);
            
            NSDictionary *dic = @{
                                  @"uid":[LoginModel shareLogin].uid,
                                  @"username":[LoginModel shareLogin].username,
                                  @"token":[LoginModel shareLogin].token,
                                  @"hid":self.hid,
                                  @"mid":self.mid,
                                  @"content":content
                                  };
            NSMutableDictionary *dicM = dic.mutableCopy;
            [dicM setValue:self.dic[@"eid"] forKey:@"eid"];
            [dicM setValue:@"1" forKey:@"eType"];
            
            [SVProgressHUD show];
            
            [AFNHelper post:SaveExam parameters:dicM success:^(id responseObject) {
                
                if ([responseObject[@"status"] isEqual:@1]) {
                    
                    [self.view makeToast:@"保存成功"];
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        
                        [self.navigationController popViewControllerAnimated:YES];
                    });
                }
                [SVProgressHUD dismiss];
                
            } faliure:^(id error) {
                
                NSLog(@"请求失败");
                [SVProgressHUD showWithStatus:ShowError];
                [SVProgressHUD dismissWithDelay:0.5];
                
            }];

        }
        
    }
    
}

- (void)submitWrong:(NSString *)content {
    
    NSDictionary *dic = @{
                          @"uid":[LoginModel shareLogin].uid,
                          @"username":[LoginModel shareLogin].username,
                          @"token":[LoginModel shareLogin].token,
                          @"content":content
                          };
    //    [SVProgressHUD show];
    [AFNHelper post:SubmitWrong parameters:dic success:^(id responseObject) {
        
        if ([responseObject[@"status"] isEqual:@1]) {
            
            
        }
        //        [SVProgressHUD showWithStatus:responseObject[@"message"]];
        //        [SVProgressHUD dismiss];
        
    } faliure:^(id error) {
        
        NSLog(@"请求失败");
        //        [SVProgressHUD showWithStatus:ShowError];
        //        [SVProgressHUD dismissWithDelay:0.5];
        
    }];
    
}

- (void)deleteMyWrong:(NSString *)wid {
    
    NSDictionary *dic = @{
                          @"uid":[LoginModel shareLogin].uid,
                          @"username":[LoginModel shareLogin].username,
                          @"token":[LoginModel shareLogin].token,
                          @"wid":wid
                          };
//    [SVProgressHUD show];
    [AFNHelper post:MyWrong parameters:dic success:^(id responseObject) {
        
        if ([responseObject[@"status"] isEqual:@1]) {
            
            
        }
//        [SVProgressHUD showWithStatus:responseObject[@"message"]];
//        [SVProgressHUD dismiss];
        
    } faliure:^(id error) {
        
        NSLog(@"请求失败");
//        [SVProgressHUD showWithStatus:ShowError];
//        [SVProgressHUD dismissWithDelay:0.5];
        
    }];
    
}

- (void)loadData1 {
    
    NSDictionary *dic = @{
                          @"uid":[LoginModel shareLogin].uid,
                          @"username":[LoginModel shareLogin].username,
                          @"token":[LoginModel shareLogin].token
                          };
    [SVProgressHUD show];
    [AFNHelper post:MyWrong parameters:dic success:^(id responseObject) {
        
        if ([responseObject[@"status"] isEqual:@1]) {
            
            self.originDatas = responseObject[@"data"];
            
            NSMutableArray *arrM = [NSMutableArray array];
            for (NSDictionary *dic in responseObject[@"data"]) {
                YYEExampleModel *model1 = [YYEExampleModel mj_objectWithKeyValues:dic[@"content"]];
                [arrM addObject:model1];
            }
            
            for (YYEExampleModel *model2 in arrM) {

                model2.answerType = @"0";
                
                for (ChoiceModel *choiceModel in model2.choice) {
                    
                    choiceModel.isChoose = NO;
                }
            }

            self.datas = arrM;

            YYEExampleModel *model = self.datas[_page-1];
            
            [_exampleView setModel:model page:_page];
            
            //刷新底部视图状态
            [self reloadFooterViewState];
            
        }
        [SVProgressHUD showWithStatus:responseObject[@"message"]];
        [SVProgressHUD dismiss];
        
    } faliure:^(id error) {
        
        NSLog(@"请求失败");
        [SVProgressHUD showWithStatus:ShowError];
        [SVProgressHUD dismissWithDelay:0.5];
        
    }];
    
}

- (void)loadData {
    
    NSDictionary *dic = @{
                          @"uid":[LoginModel shareLogin].uid,
                          @"hid":self.hid,
                          @"mid":self.mid,
                          @"username":[LoginModel shareLogin].username,
                          @"token":[LoginModel shareLogin].token
                          };
    [SVProgressHUD show];
    [AFNHelper post:GetListInfo parameters:dic success:^(id responseObject) {
        
        if ([responseObject[@"status"] isEqual:@1]) {
            
            self.datas = [YYEExampleModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"][@"content"]];
            self.dic = responseObject[@"data"];
            self.process = [responseObject[@"data"][@"process"] stringValue];
            _exampleView.process = self.process;
            
            for (YYEExampleModel *model2 in self.datas) {
                
                if (!model2) {
                    model2.answerType = @"0";

                }
                
            }
            
            if (self.type.integerValue == 2) {
                
                if (self.process.integerValue != 3) {
                    
                    [self configNavi];
                }
                else {
                    
                    [[UIApplication sharedApplication].keyWindow addSubview:self.scoreView];
                    
//                    [[UIApplication sharedApplication].keyWindow addSubview:self.scoreView1];
//                    [self.scoreView1 setText1:@"您的试卷已批改，\n批改结果如下：\n总分：100" text2:@"单选：20    多选：30判断：10    填空：40简答：50"];

                    _exampleView.userInteractionEnabled = NO;
                    // "process": 1, //进度(0未达到进度 1开始答题 2继续答题 3查看答题
                    // "type": 2, // 1是习题 2是考试
                    
                    for (YYEExampleModel *model1 in self.datas) {
                        
                        if (model1.answerType.integerValue == 1 || model1.answerType.integerValue == 2) {
                            
                            model1.isTouch = YES;
                        }
                        
                        
                    }
                }
                
            }
            else {
                // "process": 1, //进度(0未达到进度 1开始答题 2继续答题 3查看答题
                // "type": 2, // 1是习题 2是考试
                
                [self configNavi];
                
                
                for (YYEExampleModel *model1 in self.datas) {
                    
                    if (model1.answerType.integerValue == 1 || model1.answerType.integerValue == 2) {
                        
                        model1.isTouch = YES;
                    }
                    
                    
                }
            }
            
            
            YYEExampleModel *model = self.datas[_page-1];
            
            [_exampleView setModel:model page:_page];
            
            //刷新底部视图状态
            [self reloadFooterViewState];
            
        }
        [SVProgressHUD showWithStatus:responseObject[@"message"]];
        [SVProgressHUD dismiss];
        
    } faliure:^(id error) {
        
        NSLog(@"请求失败");
        [SVProgressHUD showWithStatus:ShowError];
        [SVProgressHUD dismissWithDelay:0.5];
        
    }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//刷新底部视图状态
- (void)reloadFooterViewState
{
    
    self.title = [NSString stringWithFormat:@"题目 %ld/%ld",_page, _datas.count];
    
    UIButton *btn = (UIButton *)[self.footerView viewWithTag:500];
    btn.enabled = _page == 1 ? NO : YES;
    UIButton *otButton = (UIButton *)[self.footerView viewWithTag:501];
    otButton.enabled = _page == self.datas.count ? NO : YES;
}

#pragma mark - SXQuestionsFooterViewDelegate
- (void)questionsFooterView:(HWQuestionsFooterView *)questionsFooterView didClickOptionButton:(BOOL)isNextButton
{
    
    //    //保存做题记录
    //    [self saveProgress];
    
    //更新页码
    isNextButton ? _page++ : _page--;
    
    YYEExampleModel *model = self.datas[_page-1];
    [_exampleView setModel:model page:_page];

    
    //刷新底部视图状态
    [self reloadFooterViewState];
}

- (void)getIt
{

    
    if (self.page <= self.datas.count) {
        
        NSDictionary *dic = self.originDatas[self.page-1];
        [self deleteMyWrong:dic[@"wid"]];

        if (self.page < self.datas.count) {
            self.page++;

            YYEExampleModel *model = self.datas[self.page-1];
            [self.exampleView setModel:model page:self.page];
            
            //刷新底部视图状态
            [self reloadFooterViewState];
            
        }
        else {
            NSLog(@"答题结束。。。。。。");

        }

    }

    

}

// 重写back
- (void)back {

    if (self.mark == 0) { // 查看答题和继续答题

        if (self.type.integerValue == 2) {
            
            if (self.process.integerValue != 3) {
                
                [self saveOrUp];

            }
            else {
                
                [self.navigationController popViewControllerAnimated:YES];
                
                
            }
        }
        else {
            
            [self.navigationController popViewControllerAnimated:YES];
            
            
        }
        
    }
    else {// 错题本
        
        [self.navigationController popViewControllerAnimated:YES];
        
        
    }
}

- (void)saveOrUp
{
    
    NSArray *dictArray = [YYEExampleModel mj_keyValuesArrayWithObjectArray:self.datas];
    NSString *content = [dictArray mj_JSONString];

    NSLog(@"content:%@",content);
    
    NSDictionary *dic = @{
                          @"uid":[LoginModel shareLogin].uid,
                          @"username":[LoginModel shareLogin].username,
                          @"token":[LoginModel shareLogin].token,
                          @"hid":self.hid,
                          @"mid":self.mid,
                          @"content":content
                          };
    NSMutableDictionary *dicM = dic.mutableCopy;
    [dicM setValue:self.dic[@"eid"] forKey:@"eid"];
    [dicM setValue:@"2" forKey:@"eType"];

    NSString *numStr = nil;
    
    if ([self.dic[@"num"] integerValue] > 1) {

        numStr = [NSString stringWithFormat:@"当前考试还剩%@次保存机会,请选择保存试卷或直接提交试卷",self.dic[@"num"]];

    }
    else {
        numStr = @"是否交卷";

    }
    

    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:numStr message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"保存" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [SVProgressHUD show];
        
        [dicM setValue:@"0" forKey:@"type"];

        [AFNHelper post:SaveExam parameters:dicM success:^(id responseObject) {
            
            if ([responseObject[@"status"] isEqual:@1]) {
                
                [self.view makeToast:@"保存成功"];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    
                    [self.navigationController popViewControllerAnimated:YES];
                });
            }
            //        [SVProgressHUD showWithStatus:responseObject[@"message"]];
            [SVProgressHUD dismiss];
            
        } faliure:^(id error) {
            
            NSLog(@"请求失败");
            [SVProgressHUD showWithStatus:ShowError];
            [SVProgressHUD dismissWithDelay:0.5];
            
        }];

        
        
    }];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"交卷" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [SVProgressHUD show];
        [dicM setValue:@"1" forKey:@"type"];

        [AFNHelper post:SaveExam parameters:dicM success:^(id responseObject) {
            
            if ([responseObject[@"status"] isEqual:@1]) {
                
                [self.view makeToast:@"交卷成功"];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    
                    [self.navigationController popViewControllerAnimated:YES];
                });
                
            }
            [SVProgressHUD dismiss];
            
        } faliure:^(id error) {
            
            NSLog(@"请求失败");
            [SVProgressHUD showWithStatus:ShowError];
            [SVProgressHUD dismissWithDelay:0.5];
            
        }];
        

        
    }];


    [alertController addAction:okAction];
    if ([self.dic[@"num"] integerValue] > 1) {
        
        [alertController addAction:cancelAction];

    }
    [self presentViewController:alertController animated:YES completion:nil];
}


@end

